#include <memory>

#include "EventLoopThread.h"
#include "EventLoopThreadPool.h"

EventLoopThreadPool::EventLoopThreadPool(EventLoop* baseloop,const std::string& name)
    : baseLoop_(baseloop)
    , name_(name)
    , started_(false)
    , numThreads_(0)
    , next_(0)
{

}
EventLoopThreadPool::~EventLoopThreadPool() {}

    
void EventLoopThreadPool::start(const ThreadInitCallback& cb)
{
    started_=true;
    for(int i=0;i<numThreads_;i++)
    {
        char buf[name_.size()+32];
        snprintf(buf,sizeof buf,"%s%d",name_.c_str(),i);
        EventLoopThread* t=new EventLoopThread(cb,buf);
        // 用智能指针管理 EventLoopThread 生命周期 存入threads_
        threads_.push_back(std::unique_ptr<EventLoopThread>(t));
        // 底层创建线程 绑定一个新的Eventloop 并返回loop的地址 存入loops_
        loops_.push_back(t->startLoop()); 

    }


    // 整个服务器只要一个线程 运行着baseloop
    if(numThreads_==0&&cb)
    {
        cb(baseLoop_);
    }
}


// 如果工作在多线程 baseLoop_默认以轮询的方式分配channel给subLoop
EventLoop* EventLoopThreadPool::getNextLoop()
{
    EventLoop* loop =baseLoop_;

    // 通过轮询获得下一个处理事件的loop
    if(!loops_.empty())
    {
        loop=loops_[next_++];
        if(next_>=loops_.size())
        {
            next_=0;
        }
    }

    return loop;
}

std::vector<EventLoop*> EventLoopThreadPool::getAllLoops()
{
    if(loops_.empty())
    {
        return std::vector<EventLoop*>(1,baseLoop_);
    }
    else
    {
        return loops_;
    }
}